package com.nut.spp.api.sys;

import com.nut.spp.common.Result;
import com.nut.spp.entity.SysRegion;
import com.nut.spp.service.ShopService;
import com.nut.spp.service.SysFileService;
import com.nut.spp.service.SysRegionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/system")
public class SystemController {

    @Autowired
    private SysFileService sysFileService;

    @Autowired
    private SysRegionService sysRegionService;

    @Autowired
    private ShopService shopService;

    @GetMapping("/test")
    public Result test() {
        return Result.ok();
    }

    @GetMapping("/help")
    public void help(HttpServletResponse response) {

//        File file = null;
//        try {
//            file = ResourceUtils.getFile("classpath:fonts/simsun.ttf");
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
//
//        System.out.println(file);

        StringBuilder sb = new StringBuilder();
        sb.append("\r\n shopSubmit?shopId=");
        String str = sb.toString();

        outputHtml(response, str);
    }

    private void outputHtml(HttpServletResponse response, String str) {
        response.setContentType("text/plain;charset=UTF-8");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        try {
            response.getWriter().write(str);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    @GetMapping("/shopSubmit")
    public Result shopSubmit(@RequestParam Integer shopId) {
        return shopService.submit(shopId);
    }

    /**
     * 获取子区域
     */
    @GetMapping("/region")
    public Result<List<SysRegion>> list(@RequestParam Integer pid) {
        return sysRegionService.list(pid);
    }

    /**
     * 获取子区域
     */
    @GetMapping("/regionByCode")
    public Result<List<SysRegion>> regionByCode(@RequestParam Integer code) {
        return sysRegionService.listByCode(code);
    }

    //上传文件 图片
    @PostMapping(value = "/upload")
    public Result<String> upload(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象

        return sysFileService.upload(file);
    }
}
